package com.demon.auto.utils;

import org.springframework.stereotype.Component;

import java.security.SecureRandom;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 验证码工具类
 *
 * @version 1.0
 * @author huangrz
 * @date 2025/03/24 09:09
 */
@Component
public class VerificationCodeUtil {

    /**
     * 用户ID -> [验证码, 过期时间戳]
     */
    private final static Map<Long, CodeInfo> CODE_MAP = new ConcurrentHashMap<>();
    /**
     * 验证码有效时长 5m
     */
    private final static int EXPIRE_TIMESTAMP = 300000;
    /**
     * 验证码发送间隔 1m
     */
    private final static int SEND_FREQUENCY_TIMESTAMP = 60000;

    /**
     * 验证码信息
     */
    private static class CodeInfo {
        String code;
        long expireTime;

        CodeInfo(String code, long expireTime) {
            this.code = code;
            this.expireTime = expireTime;
        }
    }

    /**
     * 生成并存储验证码（有效期5分钟）
     * @param code  验证码
     */
    public void saveCode(String code) {
        long expireTime = System.currentTimeMillis() + EXPIRE_TIMESTAMP; // 5分钟
        CODE_MAP.put(CommonUtil.getCurrentUserId(), new CodeInfo(code, expireTime));
    }

    /**
     * 获取验证码（自动检查过期）
     * @return String 验证码
     */
    public String getCode() {
        CodeInfo codeInfo = CODE_MAP.get(CommonUtil.getCurrentUserId());
        if (codeInfo == null || System.currentTimeMillis() > codeInfo.expireTime) {
            CODE_MAP.remove(CommonUtil.getCurrentUserId()); // 清理过期验证码
            return null;
        }
        return codeInfo.code;
    }

    /**
     * 删除验证码
     */
    public void deleteCode() {
        CODE_MAP.remove(CommonUtil.getCurrentUserId());
    }

    /**
     * 检查是否可以发送（60秒内不允许重复发送）
     * @return boolean
     */
    public boolean canSend() {
        CodeInfo codeInfo = CODE_MAP.get(CommonUtil.getCurrentUserId());
        if (codeInfo == null) {
            return true;
        }
        long lastSentTime = codeInfo.expireTime - EXPIRE_TIMESTAMP; // 计算上次发送时间
        return System.currentTimeMillis() - lastSentTime > SEND_FREQUENCY_TIMESTAMP; // 60秒间隔
    }

    /**
     * 生成验证码
     * @param length 验证码长度
     * @return String 纯数字验证码
     */
    public static String generateCode(int length) {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

}